import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;

import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThunderDragonServer {

	/**The port number
	 * 
	 */
	private int port;
	private  final int MAX_CLIENTS = 5;
	

    /** our thread pool */
    private ExecutorService pool;
    
	public ThunderDragonServer(final int portP){
		port = portP;

        pool = Executors.newFixedThreadPool(MAX_CLIENTS);
	}
	
	public static void main(final String[] args){
		ThunderDragonServer mainServer = new ThunderDragonServer(23451);
		mainServer.run();
		
	}
	
	public void run(){
		ServerSocket theServer; //Server's socket.
		Socket theClient= null; //Client's socket.
		BufferedReader inStream; //Read in the stream coming from client socket.
		PrintWriter outStream; //Read in the stream coming out of the client socket.
		try{

			theServer = new ServerSocket(port);
			while(true){
				theClient = theServer.accept();
				//Once accepted, we need a clientHandler to deal with all this
				ThunderDragonClientHandler chandle = 
					new ThunderDragonClientHandler(theClient);
				pool.execute(chandle);
				System.out.println(theClient.getInetAddress().getHostName());
			}
		}
		
		catch(IOException e){
            System.err.println("Error in Server Socket accept");
            e.printStackTrace();
		}
		
		finally{
			System.out.println("CODE AUDIT!");
			//Must close the sockets!
		}

	
	}
	
	public String toString(){
		return "Server";
	}
	//Streams must be flushed
}
